﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using Newtonsoft.Json.Linq;
using System.Threading;
using System.Web;
using System.Diagnostics;
using System.Net;

namespace WindowsFormsApp3
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            using (OpenFileDialog of = new OpenFileDialog())
            {
                of.Title = "选择ofd版式发票文件";
                of.Filter = "|*.ofd";
                if (DialogResult.OK == of.ShowDialog())
                {
                    txt_filepath.Text = of.FileName;
                    txt_FileName.Text = Path.GetFileName(of.FileName);
                    ReadFile();
                }
            }
        }
        /// <summary>
        /// 读取版式文件内容 并base64加密内容
        /// </summary>
        private void ReadFile()
        {
            string filepath = txt_filepath.Text;
            if(File.Exists(filepath))
            {
                string content = File.ReadAllText(filepath);
                content = Base64Helper.EncodeBase64(Encoding.GetEncoding("GB2312"), content);
                rtxt_FileContent.Text = content;
            }
        }
        /// <summary>
        /// 报文拼接
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txt_FileName.Text))
            {
                MessageBox.Show("请选择ofd文件");
                return;
            }
            JObject obj = new JObject();
            obj.Add("FileName", txt_FileName.Text);
            obj.Add("FileContent", rtxt_FileContent.Text);
            richTextBox2.Text = obj.ToString();
            string param= Base64Helper.EncodeBase64(Encoding.GetEncoding("GB2312"), richTextBox2.Text);
            richTextBox3.Text = param.Replace("+", "_");
            richTextBox1.Text = txt_address.Text + "?" + "SID=" + txt_sid.Text + "&SIDParam=" + richTextBox3.Text;
        }

        /// <summary>
        /// 发送请求
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            string rst = "";
            string SerIp = "";
            SerIp = txt_address.Text.ToString();
            if (SerIp != "")
            {
                richTextBox1.Focus();
                richTextBox1.Select(0, richTextBox1.Text.ToString().Length);
                Thread.Sleep(300);

                //http://127.0.0.1:6666/OFDParser?SID=0&SIDParam=eyJJbmZvS2luZCI6IjUxIn0=
                string postUrl = "";
                string postData = "";
                postUrl = "http://127.0.0.1:6666/OFDParser";
                postUrl = txt_address.Text.ToString();
                postData = richTextBox1.Text.ToString().Replace(postUrl + "?", "");
                string callback = "";
                callback = HttpUtility.ParseQueryString(postData).Get("callback");
                Console.WriteLine(callback);
                // Common common = new Common();
                try
                {
                    Stopwatch stopwatch1 = new System.Diagnostics.Stopwatch();
                    stopwatch1.Start();//运行时间监测

                    rst = RequestPost(postUrl, postData);

                    stopwatch1.Stop();//运行时间监测结束
                    string tolsec = stopwatch1.Elapsed.TotalSeconds.ToString("0.0000") + "秒";
                    Console.WriteLine(tolsec);
                    lbl_hs.Text = tolsec;
                }
                catch (Exception ex)
                {
                    MessageBox.Show("未能连接到http接口服务！"+ex.Message);
                    return;
                }
                string ENCMSG = "ENCMSG";
                string ENCMSGori = "";//原报文体
                ENCMSGori = rst.Replace("({\"ENCMSG\":\"", "").Replace("{\"ENCMSG\":\"", "");
                ENCMSGori = ENCMSGori.Replace("\"})", "").Replace("\"}", "");
                ENCMSGori = ENCMSGori.Replace("_", "+");//反替换
                ENCMSGori = ENCMSGori.Replace("\\", "");
                richTextBox4.Text = ENCMSGori;
                if (callback != null && callback != "")
                {
                    richTextBox4.Text = ENCMSGori.Split(new string[] { callback + "\r\n" }, StringSplitOptions.None)[1];
                }
                richTextBox4.Focus();
                richTextBox4.Select(0, richTextBox4.Text.ToString().Length);
                if (chk_AutoDecode.Checked)
                {
                    string rststr = "";
                    rststr = Decode(richTextBox4.Text.ToString());

                    richTextBox5.Text = rststr;
                    richTextBox5.Focus();
                    richTextBox5.Select(0, richTextBox5.Text.ToString().Length);
                    JObject job_RetInfo = JObject.Parse(rststr);//解析结果json
                }
            }
            else
            {
                MessageBox.Show("未能连接到云端服务，请检查并确认您的电脑可正常连接互联网，再进行此项操作。");
                return;
            }
        }
        private string Decode(string strrequest)
        {
            string ENCMSGnew = "";//解码后报文体
            try
            {
                //string strrequest = request.Text.ToString().Replace("_", "+");//反替换
                strrequest = strrequest.Replace("_", "+");//反替换
                ENCMSGnew = Base64Helper.DecodeBase64(Encoding.GetEncoding("GB2312"), strrequest);
                //Thread.Sleep(300);
            }
            catch (Exception ex) { }
            try
            {
                JObject job = JObject.Parse(ENCMSGnew);//解析成json
                ENCMSGnew = job.ToString();
            }
            catch (Exception ex)
            {
            }

            return ENCMSGnew;
        }

        /// <summary>
        /// 获得post方式请求后响应的数据
        /// <param name="postUrl">请求地址</param>
        /// <param name="data">请求带的数据</param>
        /// <returns>响应内容</returns>
        /// </summary>
        public string RequestPost(string url, string postData)
        {
            int timeout = 60 * 1000;
            Encoding requestCoding = Encoding.UTF8;
            Encoding responseCoding = Encoding.UTF8;
            string postUrl = VerifyUrl(url);
            try
            {
                //写入POSTDATE里
                byte[] byteArray = requestCoding.GetBytes(postData);
                HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(new Uri(postUrl));
                webRequest.Method = "POST";
                webRequest.Timeout = timeout;
                webRequest.ContentType = "application/x-www-form-urlencoded";
                //webRequest.ContentType = "text/xml";
                webRequest.ContentLength = byteArray.Length;
                Stream newStream = webRequest.GetRequestStream();
                newStream.Write(byteArray, 0, byteArray.Length);
                newStream.Close();
                //接收返回信息：
                HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
                StreamReader php = new StreamReader(response.GetResponseStream(), responseCoding);
                string result = php.ReadToEnd();
                return result;
            }
            catch (Exception ex)
            {
                throw new Exception(url + "\r\n" + postData + "\r\n" + ex.ToString());
                
            }
        }
        /// <summary>
        /// 验证URL
        /// </summary>
        /// <param name="url">待验证 URL</param>
        /// <returns></returns>
        private string VerifyUrl(string url)
        {
            if (string.IsNullOrEmpty(url))
                throw new Exception("URL 地址不可以为空！");
            if (url.StartsWith("http://", StringComparison.CurrentCultureIgnoreCase))
                return url;
            return string.Format("http://{1}", url);
        }

        /// <summary>
        /// 解码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button4_Click(object sender, EventArgs e)
        {
            string rststr = "";
            rststr = Decode(richTextBox4.Text.ToString());
            richTextBox5.Text = rststr;
            richTextBox5.Focus();
            richTextBox5.Select(0, richTextBox5.Text.ToString().Length);
        }

        /// <summary>
        /// 编码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button5_Click(object sender, EventArgs e)
        {
            richTextBox4.Text = "";
            string rst = richTextBox5.Text.ToString();
            rst = Encode(rst);

            if (chk_Auto_2Plus.Checked)
            {
                rst = rst.Replace("_", "+");
            }
            richTextBox4.Text = rst;
            richTextBox4.Focus();
            richTextBox4.Select(0, richTextBox4.Text.ToString().Length);
        }
        private string Encode(string content)
        {
            string strrequest = content;
            try
            {
                strrequest = Base64Helper.EncodeBase64(Encoding.GetEncoding("GB2312"), content);
            }
            catch { }
            strrequest = strrequest.Replace("+", "_");//替换+号
            return strrequest;
        }

        private void button6_Click(object sender, EventArgs e)
        {
            richTextBox1.Clear();
            richTextBox2.Clear();
            richTextBox3.Clear();
            richTextBox4.Clear();
            richTextBox5.Clear();
        }
    }
}
